package com.xjnt.frameworks.plugin.sql.criterion.expression;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.xjnt.frameworks.plugin.sql.consts.KeyWord;
import com.xjnt.frameworks.plugin.sql.criterion.Criterion;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;
import com.xjnt.frameworks.plugin.sql.criterion.SqlType;
import com.xjnt.frameworks.plugin.sql.criterion.TypedValue;

public class LikeExpression implements Criterion {

	private static final long serialVersionUID = 1L;
	private String columnName;
	private Object value;

	public LikeExpression(String columnName, Object value) {
		this.columnName = columnName;
		this.value = value;
	}

	@Override
	public String toSql(SqlCriteria criteria) {
		StringBuilder sql = new StringBuilder();
		if (criteria.isExists(columnName)) {
			sql.append(columnName);
			sql.append(" ").append(KeyWord.LIKE.getValue());
			sql.append(" ").append("?");
			return sql.toString();
		} else {
			throw new ActiveRecordException("The "+ columnName + " is not exists ");
		}
	}

	@Override
	public TypedValue[] getTypedValues(SqlCriteria criteria) {
		return new TypedValue[]{ new SqlType().getTypedValue(criteria, columnName, "%"+ value.toString() +"%") };
	}

}
